import React, { Component } from 'react';
import classNames from 'classnames';
import Radio from './index';

function getCheckedValue(children) {
  let value = null;
  let matched = false;
  React.Children.forEach(children, (radio) => {
    if (radio && radio.props && radio.props.checked) {
      value = radio.props.value;
      matched = true;
    }
  });
  return matched ? { value } : undefined;
}

export default class RadioGroup extends Component {
  static defaultProps = {
    disabled: false
  }
  constructor(props) {
    super(props);

    let value;
    if ('value' in props) {
      value = props.value;
    } else if ('defaultValue' in props) {
      value = props.defaultValue;
    } else {
      const checkedValue = getCheckedValue(props.children);
      value = checkedValue && checkedValue.value;
    }
    this.state = { value };
  }

  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      this.setState({
        value: nextProps.value
      });
    } else {
      const checkedValue = getCheckedValue(nextProps.children);
      if (checkedValue) {
        this.setState({
          value: checkedValue.value
        });
      }
    }
  }

  onRadioChange = (e) => {
    const lastValue = this.state.value;
    const { value } = e.target;
    if (!('value' in this.props)) {
      this.setState({ value });
    }

    const onChange = this.props.onChange;
    if (onChange && value !== lastValue) {
      onChange(e);
    }
  }

  render() {
    const props = this.props;
    const children = !props.children ? [] : React.Children.map(props.children, (radio) => {
      if (radio && (radio.type === Radio) && radio.props) {
        return React.cloneElement(radio, Object.assign({}, radio.props, {
          onChange: this.onRadioChange,
          checked: this.state.value === radio.props.value,
          disabled: radio.props.disabled || this.props.disabled,
        }));
      }
      return radio;
    });

    const { prefixCls = 'ant-radio-group', className = '' } = props;
    const classString = classNames(prefixCls, {
      [`${prefixCls}-${props.size}`]: props.size,
    }, className);
    return (
      <div
        className={classString}
        style={props.style}
        onMouseEnter={props.onMouseEnter}
        onMouseLeave={props.onMouseLeave}
      >
        {children}
      </div>
    );
  }
}
